namespace Digitalmes.Application.Mes;

/// <summary>
/// 产品制程表服务接口
/// </summary>
[ApiExplorerSettings(GroupName = "mes")]
public sealed class ProcRoutingProductService : IDynamicWebApiService
{
    private readonly SugarRepository<ProcRoutingProduct> _thisRepository;
    private readonly SugarRepository<ProcRouting> _routingRepo;
    private readonly SugarRepository<MdItem> _itemRepo;

    public ProcRoutingProductService(SugarRepository<ProcRoutingProduct> thisRepository, 
        SugarRepository<ProcRouting> routingRepo, 
        SugarRepository<MdItem> itemRepo)
    {
        _thisRepository = thisRepository;
        _routingRepo = routingRepo;
        _itemRepo = itemRepo;
    }

    /// <summary>
    /// 查询所有——分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<PageResult<ProcRoutingProductDto>> GetPagesAsync(PageParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .OrderByDescending(m => m.Id)
            .ToPageAsync(param.Page, param.Limit);
        return query.Adapt<PageResult<ProcRoutingProductDto>>();
    }

    /// <summary>
    /// 根据主键查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<ProcRoutingProductDto> GetAsync(long id)
    {
        var model = await _thisRepository.GetByIdAsync(id);
        return model.Adapt<ProcRoutingProductDto>();
    }

    /// <summary>
    /// 根据工业路线查询所有分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<PageResult<ProcRoutingProductDto>> GetPagesByRoutingIdAsync(RoutingProductPageParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .Includes(s => s.Product)
            .Where(s => s.RoutingId == param.RoutingId)
            .ToPageAsync(param.Page, param.Limit);
        return query.Adapt<PageResult<ProcRoutingProductDto>>();
    }

    /// <summary>
    /// 根据产品关键字产线查询
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<PageResult<ProcRoutingProductDto>> GetPagesProductByKeywordAsync(PageParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .Includes(s => s.Product)
            .Includes(s => s.Routing)
            .WhereIF(!string.IsNullOrWhiteSpace(param.Key), s => s.Product!.ItemCode.Contains(param.Key) || s.Product.ItemName.Contains(param.Key))
            .ToPageAsync(param.Page, param.Limit);
        var items = query.Adapt<PageResult<ProcRoutingProductDto>>();
        items.Items.ForEach(s =>
        {
            s.ShowDesc = $"{s.Product?.ItemName} - {s.Routing?.RoutingName}";
        });
        return items;
    }

    /// <summary>
    /// 查询可用的产品集合
    /// </summary>
    /// <param name="routingId"></param>
    /// <returns></returns>
    public async Task<PageResult<MdItemDto>> GetPagesProductsAsync(RoutingProductPageParam param)
    {
        // 查找该工艺路线对应的产线，以及该产线下所有的工艺路线
        var routing = await _routingRepo.GetByIdAsync(param.RoutingId);
        var routings = await _routingRepo.GetListAsync(s => s.LineId == routing.LineId); // 该产线下所有的工艺路线

        // 汇总这些工艺路线中已绑定的产品
        var routingIds = routings.Select(s => s.Id).ToArray();
        var boundItems = await _thisRepository.GetListAsync(s => routingIds.Contains(s.RoutingId));

        // 所有的成品扣除已绑定的产品
        var itemIds = boundItems.Select(s => s.ProductId).ToArray();
        if (param.IncludeProductId > 0)
        {
            itemIds = itemIds.Except(new[] { param.IncludeProductId }).ToArray();
        }
        var allItems = await _itemRepo.AsQueryable()
            .Where(s => s.Classify == MaterialClassifyEnum.Finished && !itemIds.Contains(s.Id))
            .ToPageAsync(param.Page, param.Limit); // 所有未绑定的成品

        return allItems.Adapt<PageResult<MdItemDto>>();
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<bool> AddAsync(ProcRoutingProductDto model)
    {
        var routing = await _routingRepo.GetByIdAsync(model.RoutingId);
        var routings = await _routingRepo.GetListAsync(s => s.LineId == routing.LineId); // 该产线下所有的工艺路线

        // 一个产品在一条产线上只能有一条工艺路线（工艺路线与产线关联，一个产品在同一条产线上只能有一条工艺路线）
        var routingIds = routings.Select(s => s.Id).ToList();
        if (await _thisRepository.IsAnyAsync(s => routingIds.Contains(s.RoutingId) && s.ProductId == model.ProductId))
        {
            Oops.ThrowBah(ErrCode.E4008);
        }

        return await _thisRepository.InsertAsync(model.Adapt<ProcRoutingProduct>());
    }

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<bool> ModifyAsync(ProcRoutingProductDto model) =>
        await _thisRepository.UpdateAsync(model.Adapt<ProcRoutingProduct>());

    /// <summary>
    /// 删除,支持批量
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    [HttpDelete]
    public async Task<bool> DeleteAsync([FromBody] List<long> ids) =>
        await _thisRepository.DeleteAsync(m => ids.Contains(m.Id));
}
